// SPDX-FileCopyrightText: Copyright 2025-2025 深圳市同心圆网络有限公司
// SPDX-License-Identifier: Apache-2.0

package roadmap_dao

import (
	"context"

	"gitcode.com/lvupclub/lvup-api/dao/common"
	"gitcode.com/lvupclub/proto-gen-go.git/src/roadmap_qa_api"
	"go.mongodb.org/mongo-driver/v2/bson"
	"go.mongodb.org/mongo-driver/v2/mongo"
	"go.mongodb.org/mongo-driver/v2/mongo/options"
)

type ThreadContentInfoDbItem struct {
	ContentId string `bson:"_id"`
	RoadmapId string `bson:"roadmapId"`
	ThreadId  string `bson:"threadId"`
	Content   string `bson:"content"`
	OptUserId string `bson:"optUserId"`
	OptTime   int64  `bson:"optTime"`
}

func (item *ThreadContentInfoDbItem) ToThreadContentInfo() *roadmap_qa_api.ThreadContentInfo {
	return &roadmap_qa_api.ThreadContentInfo{
		ContentId: item.ContentId,
		ThreadId:  item.ThreadId,
		Content:   item.Content,
		OptUserId: item.OptUserId,
		OptTime:   item.OptTime,
	}
}

type _ThreadContentDao struct {
	mc *mongo.Collection
}

func newThreadContentDao(db *mongo.Database) (*_ThreadContentDao, error) {
	mc := db.Collection(common.DB_NS_ROADMAP + "qa_thread_content")
	_, err := mc.Indexes().CreateMany(context.Background(), []mongo.IndexModel{
		{
			Keys: bson.D{{"threadId", 1}, {"optTime", 1}},
		},
		{
			Keys: bson.D{{"roadmapId", 1}},
		},
	})
	if err != nil {
		return nil, err
	}
	return &_ThreadContentDao{mc: mc}, nil
}

func (db *_ThreadContentDao) Insert(ctx context.Context, dbItem *ThreadContentInfoDbItem) error {
	_, err := db.mc.InsertOne(ctx, dbItem)
	return err
}

func (db *_ThreadContentDao) Count(ctx context.Context, threadId string) (uint32, error) {
	count, err := db.mc.CountDocuments(ctx, bson.M{"threadId": threadId})
	return uint32(count), err
}

func (db *_ThreadContentDao) List(ctx context.Context, threadId string, offset, limit int64) ([]*ThreadContentInfoDbItem, error) {
	cursor, err := db.mc.Find(ctx, bson.M{"threadId": threadId}, options.Find().SetSkip(offset).SetLimit(limit).SetSort(bson.M{"optTime": 1}))
	if err != nil {
		return nil, err
	}
	retList := []*ThreadContentInfoDbItem{}
	err = cursor.All(ctx, &retList)
	return retList, err
}

func (db *_ThreadContentDao) RemoveByThread(ctx context.Context, threadId string) error {
	_, err := db.mc.DeleteMany(ctx, bson.M{"threadId": threadId})
	return err
}

func (db *_ThreadContentDao) RemoveByRoadmap(ctx context.Context, roadmapId string) error {
	_, err := db.mc.DeleteMany(ctx, bson.M{"roadmapId": roadmapId})
	return err
}
